package com.stations.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.stations.domain.*;
import com.stations.domain.Exception;
import com.stations.domain.transmitterEntity.TransmitterResult;
import com.stations.mapper.TTransmitterExceptionMapper;
import com.stations.mapper.TTransmitterLogMapper;
import com.stations.mapper.TTransmitterMapper;
import com.stations.service.TransmitterReportService;
import com.stations.service.TransmitterSendService;
import com.stations.websocket.WebSocketService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * Describe: 发射机上报服务实现类
 * Author: Ljy
 * CreateTime: 2019/10/23
 */
@Service("TransmitterReportService")
public class TransmitterReportServiceImpl extends ServiceImpl<TTransmitterMapper, TTransmitter> implements TransmitterReportService {

    @Resource
    TTransmitterMapper transmitterMapper;
    @Resource
    TransmitterSendService transmitterSendService;
    @Resource
    TTransmitterExceptionMapper tTransmitterExceptionMapper;
    @Resource(name = "TerminalRedisTemplate")
    RedisTemplate<String, Object> redisTemplate;

    @Value("${Transmitter.Version}")
    private String version;
    @Resource
    private TTransmitterLogMapper tTransmitterLogMapper;

    @Override
    public TransmitterResult transmitterInfo(TTransmitter transmitter) {
        if("noSet".equals(transmitter.getStationCode())||"noSet".equals(transmitter.getTransCode())){
            return TransmitterResult.isNullError();
        }
        TTransmitter transmitterByDB = transmitterMapper.selectByMultiId(transmitter);
        //发射机已注册
        if (ObjectUtil.isNotEmpty(transmitterByDB)) {
            if ("0".equalsIgnoreCase(transmitterByDB.getTransReset()) || "1".equalsIgnoreCase(transmitterByDB.getTransReset())) {
                transmitterSendService.clock(transmitterByDB);
                transmitterByDB.setSendTime(new Date());
            }
            //基本信息更新
            transmitterMapper.updateByMultiId(transmitter);
        } else {
            transmitterMapper.insert(transmitter);
        }
        return TransmitterResult.success();
    }

    @Override
    public TransmitterResult transmitterStatus(RunningStatus runningStatus) {
        QueryWrapper<TTransmitter> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("station_code", runningStatus.getStationCode());
        queryWrapper.eq("trans_code", runningStatus.getTransCode());
        TTransmitter transmitterDB = transmitterMapper.selectOne(queryWrapper);
        //发射机已注册
        if (ObjectUtil.isNotEmpty(transmitterDB)) {
            transmitterDB.setSendTime(new Date());
            transmitterMapper.updateByMultiId(transmitterDB);
            //发射机已注册
            redisTemplate.boundHashOps("TransmitterRunningStatus").put(runningStatus.getStationCode() + "_" + runningStatus.getTransCode(), runningStatus);
            return TransmitterResult.success();
        } else {
            return TransmitterResult.error("未注册");
        }
    }

    @Override
    public TransmitterResult transmitterException(ExceptionList exceptionList) {
        List<Exception> list = exceptionList.getExceptionList();
        TTransmitterException transmitterException = new TTransmitterException();
        transmitterException.setStationCode(exceptionList.getStationCode());
        transmitterException.setTransCode(exceptionList.getTransCode());
        transmitterException.setSendTime(exceptionList.getSendTime());
        for (Exception exception : list) {
            transmitterException.setAlarmId(StrUtil.uuid());
            transmitterException.setStartTime(exception.getStartTime());
            transmitterException.setExceptionCode(exception.getExceptionCode());
            transmitterException.setExceptionLevel(exception.getExceptionLevel());
            transmitterException.setExceptionData(exception.getExceptionData());
            redisTemplate.boundHashOps("TransmitterException").put(exceptionList.getStationCode() + "_" + exceptionList.getTransCode() + "_" + exception.getExceptionCode(), transmitterException);
            QueryWrapper<TTransmitterException> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("station_code", transmitterException.getStationCode());
            queryWrapper.eq("trans_code", transmitterException.getTransCode());
            queryWrapper.eq("exception_code", exception.getExceptionCode());
            queryWrapper.isNull("end_time");
            TTransmitterException transmitterException1 = tTransmitterExceptionMapper.selectOne(queryWrapper);
            if (transmitterException1 == null) {
                String value = "未知";
                switch(exception.getExceptionCode()){
                    case "501":
                        value="整机输出功率报警";
                        break;
                    case "502":
                        value="整机反射功率报警";
                        break;
                    case "503":
                        value="整机驻波比报警";
                        break;
                    case "504":
                        value="整机功放电压报警";
                        break;
                    case "5051":
                        value="整机电流报警";
                        break;
                    case "506":
                        value="温度1报警";
                        break;
                    case "507":
                        value="温度2报警";
                        break;
                }
                String info = "台站：" + transmitterException.getStationCode() + "发射机：" + transmitterException.getTransCode() + "报警：" +  value;
                WebSocketService.sendMessage("transmitterexception",info);
                tTransmitterExceptionMapper.insert(transmitterException);
            }else{
                tTransmitterExceptionMapper.updateById(transmitterException1);
            }
        }
        return TransmitterResult.success();
    }

    @Override
    public TransmitterResult transmitterClearException(ExceptionList exceptionList) {
//        TTransmitterException transmitterException = (TTransmitterException) redisTemplate.boundHashOps("TransmitterException").get(exceptionList.getStationCode() + "_" + exceptionList.getTransCode() + "_" + exceptionList.getExceptionId());
//        if(ObjectUtil.isNotEmpty(transmitterException)){
        QueryWrapper<TTransmitterException> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("station_code", exceptionList.getStationCode());
        queryWrapper.eq("trans_code", exceptionList.getTransCode());
        queryWrapper.eq("exception_code", exceptionList.getExceptionId());
        queryWrapper.isNull("end_time");
        TTransmitterException transmitterException1 = tTransmitterExceptionMapper.selectOne(queryWrapper);
        if (transmitterException1 != null) {
            transmitterException1.setSendTime(exceptionList.getEndTime());
            tTransmitterExceptionMapper.updateById(transmitterException1);
        }
        redisTemplate.boundHashOps("TransmitterException").delete(exceptionList.getStationCode() + "_" + exceptionList.getTransCode() + "_" + exceptionList.getExceptionId());
//        }
        return TransmitterResult.success();
    }

    @Override
    public TransmitterResult transmitterLog(TTransmitterLog tTransmitterLog) {
        tTransmitterLog.setLogId(StrUtil.uuid());
        tTransmitterLogMapper.insert(tTransmitterLog);
        return TransmitterResult.success();
    }

    @Override
    public JSONObject protocolVersion(ExceptionLog exceptionLog) {
        TTransmitter transmitter = new TTransmitter();
        transmitter.setStationCode(exceptionLog.getStationCode());
        transmitter.setTransCode(exceptionLog.getTransCode());
        TTransmitter transmitterByDB = transmitterMapper.selectByMultiId(transmitter);
        if (ObjectUtil.isNotEmpty(transmitterByDB)) {
            JSONObject node = new JSONObject();
            node.put("version", version);
            return node;
        } else {
            JSONObject node = new JSONObject();
            node.put("version", "");
            return node;
        }
    }
}
